package com.simin.mall.utils;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.widget.EditText;
import android.widget.TextView;

import com.qbb.cqdazong.direr.appsharelib.utils.DensityUtil;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by wsm on 2024/9/11.
 * <p>
 * 文字修饰工具类
 */
public class StringUtils {

    /**
     * 正则匹配 返回值是一个SpannableString 即经过变色处理的数据
     *
     * @param text    文本
     * @param keyword 关键词
     * @return
     */
    public static SpannableString spanText(String text, String keyword) {
        SpannableString s = new SpannableString(text);
        Pattern p = Pattern.compile(keyword);
        Matcher m = p.matcher(s);
        while (m.find()) {
            int start = m.start();
            int end = m.end();
            s.setSpan(new ForegroundColorSpan(Color.parseColor("#146356")), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return s;
    }


    /**
     * 文本图片
     *
     * @param context
     * @param image
     * @return
     */
    public static Drawable getTextImage(Context context, int image) {
        Drawable drawable = context.getResources().getDrawable(image);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        return drawable;
    }


    //设置删除线
    public static void setDeleteLine(TextView textView) {
        textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
    }


    /**
     * 复制文本
     *
     * @param context
     * @param content 文本内容
     */
    public static void copyText(Context context, String content) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText(null, content);
        // 把数据集设置（复制）到剪贴板
        cm.setPrimaryClip(clipData);
    }

    /**
     * 获取数组拼接
     *
     * @param path
     * @return
     */
    public static String getSpliceString(List<String> path) {
        if (path.size() == 0) {
            return "";
        }
        StringBuilder url = new StringBuilder();
        for (int i = 0; i < path.size(); i++) {
            if (TextUtils.isEmpty(url)) {
                url.append(path.get(i));
            } else {
                url.append(",").append(path.get(i));
            }
        }
        return url.toString();
    }

    /**
     * 文本拼接数组
     *
     * @param content
     * @return
     */
    public static List<String> getSpliceList(String content) {
        if (StringUtils.isBlank(content)) {
            return new ArrayList<>();
        }
        String[] con = content.split(","); //分割
        return List.of(con);
    }


    /**
     * MD5加密取32位大写
     *
     * @param input
     * @return
     */
    public static String getMD5_32bit(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(input.getBytes());
            byte b[] = md.digest();
            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            return buf.toString();//32位的加密
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 截取指定最后一个字符之后的数据
     *
     * @param type
     * @param content
     * @return
     */
    public static String subLastContent(String type, String content) {
        String substring = content.substring(content.lastIndexOf(type));
        return substring.substring(1);
    }

    /**
     * 获取文件后缀
     *
     * @param path
     * @return
     */
    public static String getFileSuffix(String path) {
        try {
            String prefix = path.substring(path.lastIndexOf(".") + 1);
            return "." + prefix;
        } catch (Exception e) {
            e.printStackTrace();
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);
            String type = options.outMimeType;

            if (TextUtils.isEmpty(type)) {
                type = "png";
            } else {
                type = type.substring(6, type.length());
            }
            return "." + type;
        }
    }


    /**
     * 正则表达式 判断邮箱格式是否正确
     */

    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }


    /**
     * 设置最大输入多少个字符
     *
     * @param editText
     * @param maxNum
     */
    public static void setMaxEms(EditText editText, Integer maxNum) {
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxNum)});//最多可输入多少字

    }


    /**
     * 检查字符串是否是空白：<code>null</code>、空字符串<code>""</code>或只有空白字符。
     * <pre>
     * StringUtil.isBlank(null)      = true
     * StringUtil.isBlank("")        = true
     * StringUtil.isBlank(" ")       = true
     * StringUtil.isBlank("bob")     = false
     * StringUtil.isBlank("  bob  ") = false
     * </pre>
     *
     * @param str 要检查的字符串
     * @return 如果为空白, 则返回<code>true</code>
     */
    public static boolean isBlank(String str) {
        int length;

        if ((str == null) || ((length = str.length()) == 0)) {
            return true;
        }

        for (int i = 0; i < length; i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return false;
            }
        }

        return true;
    }

    /**
     * 检查字符串是否不是空白：<code>null</code>、空字符串<code>""</code>或只有空白字符。
     * <pre>
     * StringUtil.isBlank(null)      = false
     * StringUtil.isBlank("")        = false
     * StringUtil.isBlank(" ")       = false
     * StringUtil.isBlank("bob")     = true
     * StringUtil.isBlank("  bob  ") = true
     * </pre>
     *
     * @param str 要检查的字符串
     * @return 如果为空白, 则返回<code>true</code>
     */
    public static boolean isNotBlank(String str) {
        int length;

        if ((str == null) || ((length = str.length()) == 0)) {
            return false;
        }

        for (int i = 0; i < length; i++) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return true;
            }
        }

        return false;
    }


    /**
     * 设置文字颜色
     *
     * @param span
     */
    public static SpannableStringBuilder setSpan(SpannableStringBuilder span, String color) {
        span.setSpan(new ForegroundColorSpan(Color.parseColor(color)), 0, span.toString().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        return span;
    }

    /**
     * 设置文字大小
     *
     * @param span
     */
    public static SpannableStringBuilder setSpanSize(Context context, SpannableStringBuilder span, int size) {
        span.setSpan(new AbsoluteSizeSpan(DensityUtil.INSTANCE.dip2px(context, size)), 0, span.toString().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return span;
    }


}
